package com.ada.base.common;

import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.http.MediaType;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.nio.charset.StandardCharsets;

public class ControllerResponse {

    private static ObjectMapper objectMapper= new ObjectMapper();

    protected <T> ApiResponse<T> ok(T data) {
        return new ApiResponse<>(0, "success", data);
    }

    protected <T> ApiResponse<T> ok() {
        return ok(null);
    }

    protected <T> ApiResponse<T> fail(String message) {
        return new ApiResponse<>(-1, message, null);
    }

    protected <T> ApiResponse<T> accessDenied(String message) {
        return new ApiResponse<>(50014, message, null);
    }

    protected void responseText(HttpServletResponse response, Object content) throws IOException {
        response.setContentType(MediaType.APPLICATION_JSON_UTF8_VALUE);
        String result = objectMapper.writeValueAsString(content);
        byte[] bytes = result.getBytes(StandardCharsets.UTF_8);
        response.setContentLength(bytes.length);
        response.getOutputStream().write(bytes);
        response.flushBuffer();
    }
}
